package com.ziki.common.util.string;

public class HexUtil {
    public static String byteToHexStr(byte b) {
        String s = Integer.toHexString(b & 0xFF).toUpperCase();
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }

    public static String byteToHexStr(byte[] bytearr) {
        if (bytearr == null)
            return "";
        StringBuffer sb = new StringBuffer();
        for (byte b : bytearr) {
            sb.append(byteToHexStr(b));
        }
        return sb.toString();
    }

    public static byte[] hexToByte(String s) {
        if (s == null)
            return null;
        byte[] bts = new byte[s.length() / 2];
        for (int i = 0, j = 0; j < bts.length; j++) {
            try {
                bts[j] = (byte) Integer.parseInt(s.substring(i, i + 2), 16);
            } catch (NumberFormatException e) {
                bts[j] = 0x00;
                e.printStackTrace();
            }
            i += 2;
        }
        return bts;
    }
}
